import cherrypy
import sqlite3
import time

import Common

class Post(Common.Template):
	def index(self):
		return self.default()
	index.exposed = True
	
	# This function allows users to create new posts.  It requres the thread_id
	# argument.  If Reply is set, it takes the user name and content from
	# the given post.  If title and content are not set or are not valid,
	# this function shows the new post form.  Otherwise, it inserts the post
	# and then redirects back to the thread
	def New(self, thread_id = None, title = "", content = "", Reply = False):
		# Get the thread name
		thread_name = self.get_thread_name(thread_id)		
							
		if self.getLoginPermission() >= 3:	
			yield self.error("You are not logged in", True)	
		elif thread_name == None:
			yield self.error("Specified thread not found", True)
		elif self.Thread_Closed(thread_id):
			yield self.error("Thread is closed", True)	
		elif content == "" or Reply == True:
			# The user is logged in and the thread is valid, so show the input form
			
			yield self.header("Reply to %s" % thread_name)
			yield self.links()
			yield self.breadcrumbs(ThreadID = thread_id)				
			
			yield "<form method='post' action='/Post/New/%s'>" % thread_id
			yield "Post Title (optional): <br />"
			yield "<input class='monospace' type='text' name='title' size='60' value='%s' /><br />" % title
			yield "Content: <br />"
			yield "<textarea class='monospace' name='content' rows='20' cols='80'>%s</textarea><br />" % content
			yield "<input type='submit' value='Reply' />"
			yield "</form>"
			
			yield self.footer()
		else:				
			# There is content in the post, insert a new post and redirect to the thread
			cursor = cherrypy.thread_data.db.cursor() 
			
			# This PRAGMA is needed to ensure recursive triggers work
			cursor.execute("PRAGMA recursive_triggers = 1;")
			cherrypy.thread_data.db.commit()
			
			# Add the Post
			cursor.execute('''
				INSERT INTO Post (ID, Title, Content, Timestamp, UserID, ThreadID, EditTimestamp, EditUserID)
				VALUES (NULL, ?, ?, ?, ?, ?, NULL, NULL)
				''', (title, self.strip_html_bbcode(content), int(time.time()), self.getLoginID(), thread_id,))	
				
			cherrypy.thread_data.db.commit()
			
			# After this commit, the post counts will update because of the triggers
			
			# Redirect back to the thread at the new post location
			yield self.redirect("/Thread/%s#%s" % (thread_id, cursor.lastrowid))
	New.exposed = True
	
	# Reply takes the thread and post the user wants to reply to and loads
	# up the new post page with bbcode for the quote already filled out
	def Reply(self, thread_id = None, reply_id = None):
		cursor = cherrypy.thread_data.db.cursor() 
		cursor.execute("SELECT User.Username, Post.Content FROM Post, User WHERE Post.ID = ? AND Post.UserID = User.ID", (reply_id,))
		(reply_username, reply_content) = cursor.fetchone()
		
		content = "[QUOTE=%s]%s[/QUOTE]" % (reply_username, reply_content)
		return self.New(thread_id, "", content, True)
	Reply.exposed = True
	
	# Edit behaves very simililarily to New, just refer to that comment
	def Edit(self, PostID = None, NewPostTitle = "", NewPostContent = "", Delete = False):
		# Get the post info	
		cursor = cherrypy.thread_data.db.cursor() 
		
		cursor.execute("SELECT Post.Title, Post.Content, Post.UserID, Post.ThreadID FROM Post WHERE Post.ID = ?", (PostID,))
		(PostTitle, PostContent, PostUserID, thread_id) = cursor.fetchone()	
		
		if (NewPostTitle == "" and NewPostContent == "" and Delete == False) or (NewPostTitle == "" and self.post_is_first(PostID) and Delete == False):					
			if self.getLoginPermission() >= 3:	
				yield self.error("You are not logged in", True)	
			elif str(self.getLoginID()) != str(PostUserID) and self.getLoginPermission() >= 2:
				yield self.error("You don't have suffecient permission to edit that post", True)
			elif PostTitle == None and PostContent == None:
				yield self.error("Specified post does not exist", True)
			elif self.Thread_Closed(thread_id):
				yield self.error("Thread is closed", True)	
			else:		
				# The user is logged in and the post is valid, so show the input form
				
				yield self.header("Edit Post")
				yield self.links()
				yield self.breadcrumbs(ThreadID = thread_id)				
				
				# This forum has hidden userid and threadid values to feed to the SavePost function
				yield "<form method='post' action='/Post/Edit/%s'>" % PostID
				if self.post_is_first(PostID):
					yield "Post Title: <br />"
				else:
					yield "Post Title (optional): <br />"
				yield "<input class='monospace' type='text' name='NewPostTitle' size='60' value='%s'/><br />" % PostTitle 
				yield "Content: <br />"				
				yield "<textarea class='monospace' name='NewPostContent' rows='20' cols='80'>%s</textarea><br />" % PostContent	
				yield "<input type='submit' value='Update Post' />"
				if not self.post_is_first(PostID):
					yield "<input type='submit' name='Delete' value='Delete Post' />"
				yield "</form>"
				
				yield self.footer()
		else:	
			if self.getLoginPermission() >= 3:	
				yield self.error("You are not logged in", True)	
			elif str(self.getLoginID()) != str(PostUserID) and self.getLoginPermission() >= 2:
				yield self.error("You don't have suffecient permission to edit that post", True)
			elif PostTitle == None and PostContent == None:
				yield self.error("Specified post does not exist", True)
			elif self.Thread_Closed(thread_id):
				yield self.error("Thread is closed", True)	
			else:
				if Delete:
					# This PRAGMA is needed to ensure recursive triggers work
					cursor.execute("PRAGMA recursive_triggers = 1;")
					cherrypy.thread_data.db.commit()
					
					cursor.execute("DELETE FROM Post WHERE Post.ID = ?", (PostID,))				
					cherrypy.thread_data.db.commit()
					
					# After this commit, the post counts will update because of the triggers
									
					# Redirect back to the thread at the new post location
					yield self.redirect("/Thread/%s" % (thread_id))
					
				else:
					# Add the Post
					cursor.execute('''UPDATE Post SET Title = ?, Content = ?, EditTimestamp = ?, EditUserID = ? WHERE Post.ID = ?''', (self.strip_html_bbcode(NewPostTitle), NewPostContent, int(time.time()), self.getLoginID(), PostID,))	
						
					cherrypy.thread_data.db.commit()					
					
					cursor.execute("SELECT Post.ThreadID FROM Post WHERE Post.ID = ?", (PostID,))
					threadid = cursor.fetchone()[0]
					
					# Redirect back to the thread at the new post location
					yield self.redirect("/Thread/%s#%s" % (threadid, PostID))			
	Edit.exposed = True
	
	# This function takes in a post and determines if it is the first post.  
	# This allows us to figure out if the user should be allowed to delete the post.  
	def post_is_first(self, PostID):
		cursor = cherrypy.thread_data.db.cursor() 
		cursor.execute("SELECT MIN(Post.ID) FROM Post WHERE Post.ThreadID = (SELECT Post.ThreadID FROM Post WHERE Post.ID = ?)", (PostID,))
		
		FirstPostID = cursor.fetchone()[0]
		
		return str(FirstPostID) == str(PostID)
		
				
